#include <bits/stdc++.h>

#define in read()
#define fi first
#define se second
#define pb push_back
#define rep(i, x, y) for(int i = (x); i <= (y); i++) 
#define per(i, x, y) for(int i = (x); i >= (y); i--)

using namespace std;

using ll = long long;
using db = double;
using pii = pair < int , int >;
using vec = vector < int >;
using veg = vector < pii >;

int read() {
	int x = 0; bool f = 0; char ch = getchar(); while(!isdigit(ch)) f |= ch == '-', ch = getchar(); 
	while(isdigit(ch)) x = x * 10 + (ch ^ 48), ch = getchar(); return f ? -x : x;
}

const int N = 1e5 + 10;

int x[N], y[N], n, cnt, fa[N];

int gf(int x) { return fa[x] == x ? x : fa[x] = gf(fa[x]); }
struct edge { int u, v, w; } e[N << 2];
set < pii > dx, dy;

int main() {
#ifndef ONLINE_JUDGE
	freopen("1.in", "r", stdin);
#endif
	n = in; rep(i, 1, n) x[i] = in, y[i] = in, dx.insert({ x[i], i }), dy.insert({ y[i], i });
	rep(i, 1, n) fa[i] = i;
	rep(i, 1, n) {
		dx.erase({ x[i], i }); dy.erase({ y[i], i });
		auto it = dx.lower_bound({ x[i], 0 }); if(it != dx.end()) e[++cnt] = (edge) { i, it->se, it->fi - x[i] };
		if(it != dx.begin()) { it--; e[++cnt] = (edge) { i, it->se, x[i] - it->fi }; }
		it = dy.lower_bound({ y[i], 0 }); if(it != dy.end()) e[++cnt] = (edge) { i, it->se, it->fi - y[i] };
		if(it != dy.begin()) { it--; e[++cnt] = (edge) { i, it->se, y[i] - it->fi }; }
		dx.insert({ x[i], i }); dy.insert({ y[i], i });
	}
	sort(e + 1, e + cnt + 1, [](auto a, auto b) { return a.w < b.w; });
	ll ans = 0;
	rep(i, 1, cnt) {
		int x = e[i].u, y = e[i].v;
		if(gf(x) != gf(y)) { ans += e[i].w; fa[gf(x)] = gf(y); }
	} cout << ans << endl;
	return 0;
}
